package com.example.light.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.light.system.common.Result;
import com.example.light.system.entity.role;
import com.example.light.system.entity.rolePermission;
import com.example.light.system.mapper.PermissionMapper;
import com.example.light.system.mapper.RoleMapper;
import com.example.light.system.mapper.RolePermissionMapper;
import com.example.light.system.service.impl.IRoleService;
import com.example.light.system.vo.insertRolePermissionMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

@Service
public class roleService extends ServiceImpl<RoleMapper, role> implements IRoleService {
    @Resource
    RoleMapper roleMapper;
    @Resource
    PermissionMapper permissionMapper;
    @Resource
    RolePermissionMapper rolePermissionMapper;


    /**
     * 返回数据库中所有的角色信息
     * @return
     */
    public Result<List<role>> searchAllRole(){
        List<role> roles = roleMapper.selectList(null);
        return Result.success(roles);
    }

    /**
     * 新增角色权限映射信息
     *
     * @param rolePermission
     * @return
     */
    public Result<Integer> addRolePermission(insertRolePermissionMapper rolePermission){
        List childPermissionIdSet = rolePermission.getPermissionIdSet();
        // 查询父路由id
        HashSet permissionIdSet = permissionMapper.batchQueryParentId(childPermissionIdSet);
        // 遍历子路由id添加权限结果集
        Iterator iterator = childPermissionIdSet.iterator();
        while (iterator.hasNext()){
            Object next = iterator.next();
            if (!permissionIdSet.contains(next)) {
                permissionIdSet.add(next);
            }
        }
        // 先查询角色再次之前是否赋予过权限
        QueryWrapper<rolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",rolePermission.getRoleId());
        List<rolePermission> rolePermissions = rolePermissionMapper.selectList(wrapper);
        // 如果角色有权限，则删除角色原有所有权限
        if (rolePermissions.size() != 0){
            QueryWrapper<rolePermission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id",rolePermission.getRoleId());
            rolePermissionMapper.delete(queryWrapper);
        }
        // 批量添加角色权限映射信息
        Integer integer = rolePermissionMapper.batchInsertRolePermission(rolePermission.getRoleId(), permissionIdSet);
        return Result.success(integer);
    }
}
